<?php
/**
 * 微信支付.
 * 商户系统先调用该接口在微信支付服务后台生成预支付交易单，
 * 返回正确的预支付交易回话标识后再在APP里面调起支付。
 * User: 广州利大科技 chan
 * Date: 2017/8/7 18:10
 */

namespace app\api\service;
use app\api\service\WxNotify as WxNotifyService;
use app\api\service\CLogFileHandler;
use app\api\logic\Order;
use think\Loader;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.JsApiPay.php');
Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class WxPay
{
    public $NOTIFY_URL = 'http://aifood.gzldrj.com/api/pay/wechat/notice';
    public function WxAppPay($data)
    {

        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        //$input->SetAttach($orderData['attach']);
        $input->SetOut_trade_no($data['pay_sn']);
        $input->SetTotal_fee($data['charges']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //$input->SetGoods_tag($orderData['goods_tag']);
        $input->SetNotify_url($this->NOTIFY_URL);
        $input->SetTrade_type("APP");
        //统一下单
        $order = \WxPayApi::unifiedOrder($input);
		

        $jsApiParametersData['appid'] = $order['appid'];
        $jsApiParametersData['mch_id'] = $order['mch_id'];
        $jsApiParametersData['prepay_id'] = $order["prepay_id"];
        $jsApiParameters = $tools->GetAppApiParameters($jsApiParametersData);
        return $jsApiParameters;
    }


    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);

        if (array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS"
        ) {
            return true;
        }
        return false;
    }
    //微信通知
    public function notify()
    {
		$data = [];
		$input = file_get_contents("php://input");
		if (!empty($input) && empty($_GET['out_trade_no'])) {
			$obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
			$data = json_decode(json_encode($obj), true);
		}
		
		//根据$data处理自己所要的逻辑
	    //初始化日志
        $logHandler = new CLogFileHandler(dirname(__FILE__) . DIRECTORY_SEPARATOR . "./../../../extend/WxPay/logs/" . date('Y-m-d', time()) . ".log");
        Log::Init($logHandler, 15);
        Log::DEBUG("call back:" . json_encode($data));

        if (!array_key_exists("transaction_id", $data)) {
			Log::WARN("输入参数不正确");
            return false;
        }
        //查询订单，判断订单真实性
        if (!$this->Queryorder($data["transaction_id"])) {
			Log::WARN("找不到支付单号：" . $data['transaction_id'] . "的订单");
            return false;
        }
		
        if ($data['result_code'] == 'SUCCESS') {
            $model_pay_log = db('pay_log');
            $pay_log = $model_pay_log->where(array('pay_sn' => $data['out_trade_no']))->find();
			
            if (empty($pay_log)) {
                Log::WARN("找不到支付单号：" . $data['out_trade_no'] . "的订单");
                return false;
            }
            if ($pay_log['status'] == PAY_SUCCESS) {
                Log::INFO("该订单已支付，支付单号：" . $data['out_trade_no'] . "的订单",'info');
                return true;
            }
		
            if(($pay_log['money']*100) != $data['total_fee']){
                Log::WARN("该订单的金额与实际支付不符，支付单号：" . $data['out_trade_no'] . "的订单",'info');
                return false;
            }
            return (new Order())->afterPay($pay_log,1);
        } else {
            // 如果出现异常，向微信返回false，请求重新发送通知
            return false;
        }
        return true;
    }
    //支付跳转
    public function forwardUrl()
    {
        header("Content-type: text/html; charset=utf-8");
        $result = I('get.result_code');
        if($result == 'SUCCESS') {//支付成功

        }else {

        }
    }
}